<?php

namespace app\common\dao\system\upload;

use think\db\BaseQuery;
use app\common\dao\BaseDao;
use app\common\model\system\upload\SystemUploadFileModel;
use app\common\repositories\system\upload\SystemUploadGroupRepository;

class SystemUploadFileDao extends BaseDao
{

    /**
     * @return SystemUploadFileModel
     */
    protected function getModel(): string
    {
        return SystemUploadFileModel::class;
    }

    /**
     * 条件修改
     *
     * @param $where
     * @param $data
     * @return int
     * @throws \think\db\exception\DbException
     */
    public function whereUpdate($where, $data)
    {
        return $this->getModel()::getDB()->where($where)->update($data);
    }

    /**
     * @param array $where
     * @return BaseQuery
     */
    public function search(int $propertyId, array $where)
    {
        return $this->getModel()::getDB()
            ->when($propertyId !== null, function ($query) use ($propertyId) {
                $query->where('property_id', $propertyId);
            })
            ->when(isset($where['group_id']) && $where['group_id'] >= 0, function ($query) use ($where) {
                /**
                 * @var SystemUploadGroupRepository $groupRepository
                 */
                $groupRepository = app()->make(SystemUploadGroupRepository::class);
                $query->where('group_id', 'in', array_merge([$where['group_id']], $groupRepository->getChildIds($where['group_id'])));
            })->when(isset($where['show_src']) && $where['show_src'] !== '', function ($query) use ($where) {
                $query->where('show_src', $where['show_src']);
            })->when(isset($where['storage_type']) && $where['storage_type'] !== '', function ($query) use ($where) {
                $query->where('storage_type', $where['storage_type']);
            })->when(isset($where['file_type']) && is_array($where['file_type']), function ($query) use ($where) {
                $query->where('file_type', 'in', $where['file_type']);
            })->when(isset($where['time']) && $where['time'] !== '', function ($query) use ($where) {
                $times = explode(' - ', $where['time']);
                $startTime = strtotime($times[0]);
                $endTime = strtotime($times[1]);
                $query->whereBetween('add_time', [$startTime, $endTime]);
            });
    }

}
